<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\db\Query;
use think\Model;

/**
 * Class CashcardCate
 * @package app\admin\model
 * Author FashionJune
 */
class CashcardCate extends TimeModel
{

    protected $name = "cashcard_cate";

    public function cards()
    {
        return $this->hasMany('app\admin\model\CashcardUser', 'cate_id', 'id');
    }

    public function admin()
    {
        return $this->belongsTo('app\admin\model\SystemAdmin', 'from_admin', 'id');
    }

    public static function onBeforeWrite(Model $model)
    {
        $model->related_store = $model->related_store ?? '';
        is_array($model->tips) && ($model->tips = implode('|', $model->tips));
        is_array($model->attention) && ($model->attention = implode('|', $model->attention));
    }

    public static function onAfterRead(Model $model)
    {
        //券类型
        $model->type_name = self::getCardType($model->card_type);
        //使用范围
        if ($model->related_cate) {
            $map_cate = [
                'id' => str2arr($model->related_cate)
            ];
            $cate_list = arr2str(ShopCate::where($map_cate)->cache()->column('title'));
        } else {
            $cate_list = '全场通用';
        }
        $model->cate_list = $cate_list;
        //过期时间
        isset($model->expire_time) && ($model->expire_at = date('Y-m-d H:i:s', $model->expire_time));

        if (isset($model->cards)) {//统计具体数量
            $model->expired_num = $model->send_num = $model->used_num = 0;
            foreach ($model->cards as $card) {
                ($card->to_user > 1) && $model->send_num++;
                ($card->status == 1 || $card->status == -2) && $model->used_num++;
                ($card->status == -1) && $model->expired_num++;
            }
            $model->rest_num = $model->num - $model->send_num;
        }
        //使用说明
        $model->tips_arr = json_encode(str2arr($model->tips ?? ''));
        //注意事项
        $model->attention_arr = json_encode(str2arr($model->attention ?? ''));
    }

    /**
     * @title 数据库写入前
     * @param Model $model
     * @author FashionJune
     */
    public static function onAfterInsert(Model $model)
    {
        //添加代金券
        if ($model->num > 1) {
            CashcardUser::init()->addCashCards($model);
        }
    }


    /**
     * @title 获取卡类型
     * @param string $type
     * @return string|string[]
     * @author FashionJune
     */
    public static function getCardType($type = 'all')
    {
        $type_arr = ['1' => '通用券', '2' => '分类券'/*, 3 => '商家券'*/];
        if ($type == 'all') {
            return $type_arr;
        } else {
            return ($type_arr[$type]) ?? '';
        }
    }

    /**
     * @title 批量分发给管理员
     * @param int $cate_id
     * @param int $admin_id
     * @param int $num
     * @author FashionJune
     */
    public function sendToAdmin(int $cate_id, int $admin_id, int $num)
    {
        $map_cards = [
            'cate_id' => $cate_id,
            'status' => 0,
            'to_user' => 0,
            'to_admin' => session('admin_id')['id'] ?? 1
        ];
        $cards_num = CashcardUser::where($map_cards)->field(['id', 'cate_id', 'status', 'to_user', 'to_admin'])->count();
        if ($cards_num < $num) {
            return error('可用数量不足');
        }

    }

    /**
     * @title 批量分发给消费者
     * @param int $cate_id
     * @param int $user_id
     * @param int $num
     * @author FashionJune
     */
    public function sendToUser(int $cate_id, int $user_id, int $num)
    {

    }


    /**
     * @title 获取编码
     * @author FashionJune
     */
    public function getCashCardCode()
    {
        return substr(md5(random_int(100000, 999999) . md5(time())), 0, 16);
    }

    /**
     * @title 更新数量
     * @author FashionJune
     * @param $id
     * @param $after
     * @param $before
     */
    public function updateCardNum($id, $before)
    {
        $cate = $this->find($id);
        $inc = (int)($cate->num - $before);
        if ($inc > 0) {//增加
            $insert_data = [];
            for ($i = 1; $i <= $inc; $i++) {
                $insert_data[] = [
                    'cate_id' => $cate->id,
                    'code' => $this->getCashCardCode(),
                    'related_cate' => $cate->related_cate ?? '',
                    'related_store' => $cate->related_store ?? '',
                    'expire_time' => $cate->expire_time ?? (time() + 8640000)
                ];
            }
            CashcardUser::init()->saveAll($insert_data);
        } else {
            $del_num = $before - $cate->num;
            $map_del = [
                ['cate_id', '=', $id],
                ['status', '=', 0],
                ['to_user', '=', 0]
            ];
            CashcardUser::where($map_del)->limit($del_num)->delete();
        }
    }



}